package com.laicunba.event.listener;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.json.simple.JSONArray;
import org.json.simple.parser.JSONParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import com.laicunba.event.WithdrawEvent;
import com.laicunba.pojo.FinancingTargetBidDO;
import com.laicunba.pojo.RegistryDO;
import com.laicunba.pojo.UserDO;
import com.laicunba.service.MobileMessageService;
import com.laicunba.service.RegistryService;
import com.laicunba.service.TemplateService;
import com.laicunba.service.UserService;

@Component
public class ReinvestActivity2Listener implements ApplicationListener<WithdrawEvent> {
	private static final Logger LOG = Logger.getLogger(ReinvestActivity2Listener.class);

	@Autowired
	private RegistryService registryService;
	@Autowired
	private TemplateService templateService;
	@Autowired
	private UserService userService;
	@Autowired
	private MobileMessageService mobileMessageService;

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public void onApplicationEvent(WithdrawEvent event) {
		try {
			if (event.getSource() instanceof FinancingTargetBidDO) {
				FinancingTargetBidDO bidDO = (FinancingTargetBidDO) event.getSource();
				DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				RegistryDO onOffRegistry = registryService.get(RegistryDO.class, "act.reinvest-activity2.open");
				if(bidDO != null && "CPB".equalsIgnoreCase(bidDO.getType()) && !"ACTIVITY".equalsIgnoreCase(bidDO.getPayMark()) && onOffRegistry != null) {
					JSONArray actTimeArray = (JSONArray)new JSONParser().parse(onOffRegistry.getVal());
					if(actTimeArray != null) {
						Map<String, String> tempMap = (Map<String, String>) actTimeArray.get(0);
						if(tempMap != null && new Date().compareTo(sdf.parse(tempMap.get("start_time"))) >= 1 && new Date().compareTo(sdf.parse(tempMap.get("end_time"))) < 1) {
							Map param = new HashMap();
							String msg = templateService.simpleMerge("复投有礼第二期！活动期间复投加息2%25，更有好礼相送！猛戳 http://8.laicunba.com/h5/activity/reinvest_activity2.htm", param);
							UserDO user = userService.get(UserDO.class, bidDO.getBidUserId());
							mobileMessageService.sendMsgAsync(user.getMobile(), msg);
						}
					}
				}
			}
		} catch (Exception e) {
			LOG.error("【复投有礼第二期】回款短信发送异常", e);
		}
	}
	
}
